<template>
  <div class="market-price">
    <a-space class="button-group">
      <a-button type="primary" @click="getPirce" :loading="loading">
        获取价格
      </a-button>
      <a-button @click="autoCreate">一键制造</a-button>
    </a-space>

    <a-list v-if="outputText.length" bordered class="output-list">
      <a-list-item v-for="text in outputText" :key="text">
        {{ text }}
      </a-list-item>
    </a-list>

    <a-table
      :columns="columns"
      :data-source="formatTableData"
      :pagination="false"
      :rowClassName="(record) => (record.hasLirun ? 'has-profit' : '')"
      :scroll="{ x: true, y: 550 }"
      class="price-table"
      size="middle"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex.includes('city')">
          <div class="price-cell">
            <span :style="{ color: record[column.dataIndex].minPriceColor }">
              {{ record[column.dataIndex].isMinSellPrice ? "卖" : "" }}
              <a-tooltip :title="record[column.dataIndex].sell_price_min_date">
                {{ record[column.dataIndex].sell_price_min }}
              </a-tooltip>
            </span>
            <span :style="{ color: record[column.dataIndex].maxPriceColor }">
              {{ record[column.dataIndex].isMaxBuyPrice ? "买" : "" }}
              <a-tooltip :title="record[column.dataIndex].buy_price_max_date">
                {{ record[column.dataIndex].buy_price_max }}
              </a-tooltip>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script>
import items from "./items/index";
import { getPrice } from "../request";
import dayjs from "dayjs";
import {
  getCityName,
  getCityNameByAlias,
  getMakeLirun,
  getOutputInfo,
} from "../utils";
const currentData = items[0];
const cacheKey = "marketPrice";

export default {
  emits: ["search"],
  data() {
    return {
      loading: false,
      columns: [
        {
          title: "Item",
          dataIndex: "name",
          key: "name",
          fixed: "left",
          width: 160,
        },
        ...["city1", "city2", "city3", "city4", "city5", "city6"].map(
          (city) => {
            return {
              title: getCityNameByAlias(city),
              dataIndex: `city_${city}`,
              key: city,
              width: 120,
            };
          }
        ),
      ],
      tableData: [
        {
          id: "CLOTH",
          citys: [
            {
              id: "chengshi1",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi2",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengsh3",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi4",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi5",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
            {
              id: "chengshi6",
              minPrice: 1,
              minPriceDate: "2021-01-01",
              maxPrice: 1,
              maxPriceDate: "2021-01-01",
            },
          ],
        },
      ],
      lastGetTime: "",
      refreshed: false,
      outputText: [],
    };
  },
  computed: {
    formatTableData() {
      return this.tableData.map((item) => {
        console.log("item: ", item);
        const formattedItem = {
          key: item.id,
          name: `${item.id.slice(0, 2)}${item.name || ""}`,
          hasLirun: item.hasLirun,
        };

        item.citys.forEach((city, index) => {
          formattedItem[`city_city${index + 1}`] = city;
          // 将每个城市里面的数据的时间转成本地时间
          formattedItem[`city_city${index + 1}`].sell_price_min_date = dayjs(
            city.sell_price_min_date
          ).format("YYYY-MM-DD HH:mm:ss");
          formattedItem[`city_city${index + 1}`].buy_price_max_date = dayjs(
            city.buy_price_max_date
          ).format("YYYY-MM-DD HH:mm:ss");
        });

        return formattedItem;
      });
    },
  },
  mounted() {
    console.log("this.", this.columns);
    const cacheData = localStorage.getItem(cacheKey);
    if (cacheData) {
      const _cacheData = JSON.parse(cacheData);
      this.complete(_cacheData);
    }
  },
  methods: {
    autoCreate() {
      // if (!this.refreshed) {
      //   alert("请刷新数据");
      //   return;
      // }
      const result = getMakeLirun([...this.tableData], 2000, 10.5, 0.36);
      const outputText = [];
      result.forEach((item) => {
        const outputInfo = getOutputInfo(item);
        outputText.push(outputInfo);
      });
      this.outputText = outputText;
    },
    complete(data) {
      if (!Array.isArray(data) || data.length === 0) {
        this.$message.warning("没有获取到数据");
        return;
      }

      const items = [];
      data.forEach((item) => {
        if (!item.item_id) return;

        const id = item.item_id;
        const findIndex = items.findIndex((it) => it.id === id);
        if (findIndex > -1) {
          items[findIndex].citys.push(item);
        } else {
          items.push({
            id: id,
            citys: [item],
          });
        }
      });

      // 确保每个项目都有完整的 citys 数组
      items.forEach((item) => {
        if (!Array.isArray(item.citys)) {
          item.citys = [];
        }
      });

      let newData = this.setColor(items);
      newData = this.setName(newData);
      this.tableData = newData;
    },
    setColor(data) {
      data.forEach((item) => {
        item.citys.forEach((city) => {
          const minPriceDate = city.buy_price_min_date;
          const minPriceColor = this.getColorByDate(new Date(minPriceDate));
          const maxPriceDate = city.sell_price_max_date;
          const maxPriceColor = this.getColorByDate(new Date(maxPriceDate));
          city.minPriceColor = minPriceColor;
          city.maxPriceColor = maxPriceColor;
        });
        let hasLirun = false;
        const minSellPrice = Math.min(
          ...item.citys.map((item) =>
            item.sell_price_min === 0 ? 999999999 : item.sell_price_min
          )
        );
        const maxBuyPrice = Math.max(
          ...item.citys.map((item) =>
            item.buy_price_max === 0 ? 0 : item.buy_price_max
          )
        );
        if (
          (maxBuyPrice - minSellPrice - maxBuyPrice * 0.04) * 1500 >
          1000 * 1000
        ) {
          hasLirun = true;
        }
        hasLirun &&
          item.citys.forEach((item) => {
            if (item.sell_price_min === minSellPrice) {
              item.isMinSellPrice = true;
            }
          });
        hasLirun &&
          item.citys.forEach((item) => {
            if (item.buy_price_max === maxBuyPrice) {
              item.isMaxBuyPrice = true;
            }
          });
        item.hasLirun = hasLirun;
      });
      return data;
    },
    // 根据id获取名称
    setName(newData) {
      newData.forEach((item) => {
        currentData.list.forEach((it) => {
          if (it.list && Array.isArray(it.list)) {
            const name = it.list.find((it) => it.id === item.id)?.name;
            if (name) {
              item.name = name;
            }
          }
        });
      });
      return newData;
    },
    // 根据时间获取颜色，离当前时间越近，颜色越深
    getColorByDate(date) {
      const now = new Date();
      let diff = (now.getTime() - date.getTime()) / 1000;
      diff = diff - 8 * 3600;
      if (diff < 3600) {
        return "#000";
      } else if (diff < 3 * 3600) {
        return "#333";
      } else if (diff < 7 * 3600) {
        return "#666";
      } else if (diff < 15 * 3600) {
        return "#999";
      } else {
        return "#ccc";
      }
    },
    async getPirce() {
      if (
        this.lastGetTime &&
        new Date().getTime() - this.lastGetTime < 60 * 1000
      ) {
        this.$message.warning("1分钟内只能获取一次");
        return;
      }

      this.loading = true;
      try {
        const idsList = [];
        currentData.list.forEach((item) => {
          const ids = item.list
            .filter((fi) => fi.level === 2)
            .map((li) => {
              return li.id;
            });
          idsList.push(...ids);
        });
        let orderList = idsList.sort();
        orderList = orderList.filter(
          (item) => item.indexOf("T7") === -1 && item.indexOf("T8") === -1
        );
        const { data } = await getPrice({
          item: orderList.join(","),
          hasRed: true,
        });
        this.refreshed = true;
        localStorage.setItem(cacheKey, JSON.stringify(data));
        this.complete(data);
      } catch (error) {
        this.$message.error("获取价格失败");
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style>
.market-price {
  padding: 24px;
  height: 90vh;
  overflow-y: auto;
  background: #f0f2f5;
}

.button-group {
  margin-bottom: 16px;
}

.output-list {
  margin-bottom: 16px;
  background: #fff;
}

.price-table {
  background: #fff;
}

.price-cell {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.has-profit {
  background-color: #fff1f0;
}

.has-profit td {
  border-color: #ff4d4f !important;
}

:deep(.ant-table-cell) {
  padding: 8px !important;
}
</style>
